//
//  MyMap1ViewController.m
//  MyMap1
//
//  Created by Seok-Kyu Kong on 10. 01. 02.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//
// MapKit 사용예제: 
// http://icodeblog.com/2009/12/21/introduction-to-mapkit-in-iphone-os-3-0/
// http://blog.objectgraph.com/index.php/2009/04/03/iphone-sdk-30-playing-with-map-kit-part-2/
// 구글 주소좌표변환예제: http://ggungs.com/tag/Geocode
// 예제: http://maps.google.co.kr/maps/geo?q=주소&output=xml
// 구글 맵api FAQ: http://code.google.com/apis/maps/faq.html
// NSMXMLParser 사용: http://cocoadev.tistory.com/245
// - http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/XMLParsing/XMLParsing.html
// - http://www.radupoenaru.com/objective-c-use-nsxmlparser/
// 한글이 포함된 url처리: http://alones.kr/tag/nsurlrequest
//


#import "MyMap1ViewController.h"


@implementation MyMap1ViewController

@synthesize mapView;
@synthesize searchField;

- (IBAction) textFieldDoneEditing:(id)sender
{
	[sender resignFirstResponder];
}

// 경고창 실행
- (void) MyAlert: (NSString *)msg
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"경고" 
		message:msg 
		delegate:nil 
		cancelButtonTitle:@"닫기!" 
		otherButtonTitles:nil];
	
	[alert show];
	[alert release];	
}


// 지도 또는 위성 에 따른 맵 타입을 변경한다.
- (IBAction) setMap:(id)sender
{
	NSString *title = [sender titleForState:UIControlStateNormal];
	
	if([title isEqualToString:@"지도"] == YES)
		mapView.mapType = MKMapTypeStandard;
	else if([title isEqualToString:@"위성"] == YES)
		mapView.mapType = MKMapTypeSatellite;
	
	NSLog(@"Button title: %@", title);
}

- (IBAction) markAddress:(id)sender
{
	MyAnnotation *mark = [[MyAnnotation alloc] initWithCoordinate:resultCoord];
	[mark setTitle: [searchField text]];
	mark.subtitle = @"서브 타이틀";
	[mapView addAnnotation:mark];
	[mark release];
	
	// 사파리 웹브라우저 실행 (기존 앱 종료)
	//NSURL *url = [NSURL URLWithString:@"http://www.apple.com"];
	//[[UIApplication sharedApplication] openURL:url];
}
#pragma mark NSXMLParser 메소드
// 엘리먼트 파싱 시작될 때 호출
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
	namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
	attributes:(NSDictionary *)attributeDict 
{
    if ([elementName isEqualToString:@"code"] || [elementName isEqualToString:@"coordinates"])
		[xmlValue setString:@""];
}

// value의 문자값을 만날 때 호출, 문자가 xmlValue에 하나씩 추가함
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
        [xmlValue appendString:string];
}

// value 값 파싱이 끝나면 호출됨
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
    if ([elementName isEqualToString:@"code"]) 
	{
        [resultCode setString:xmlValue];
		NSLog(@"xmlValue: %@", xmlValue);	// <code>200</code>
    } 
	else if ([elementName isEqualToString:@"coordinates"]) 
	{
		NSArray *listItems = [xmlValue componentsSeparatedByString:@","];
		resultCoord.longitude =  [[listItems objectAtIndex:0] doubleValue];
		resultCoord.latitude = [[listItems objectAtIndex:1] doubleValue];
		
		//[listItems release];
		//NSLog(@"xmlValue: %@", xmlValue);	// <coordinates>126.8469571,37.4752659,0</coordinates>
		NSLog(@"latitude: %f, longtitude: %f", resultCoord.latitude, resultCoord.longitude);
    }
}

// 주소정보를 좌표 정보로 변경 후 해당 위치로 변경한다.
- (IBAction) searchAddress:(id)sender
{
	// xml 변수값 초기화
	xmlValue = [[NSMutableString alloc] init];
	resultCode = [[NSMutableString alloc] init];
		
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

	NSString *searchAddress = searchField.text;
	NSString *urlString = [[NSString alloc] initWithFormat: @"http://maps.google.co.kr/maps/geo?q=%@&output=xml", searchAddress];
	NSString *escapedUrl = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

	//NSURL *url = [NSURL URLWithString:urlString]; 
	NSURL *url = [NSURL URLWithString:escapedUrl];
	NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
	
	NSData *urlData;
	NSURLResponse *response;
	NSError *error;
	urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

	//NSLog(@"검색주소: %@", searchAddress);
	//NSLog(@"url: %@", urlString);
	
	if(!urlData)
	{
		[self MyAlert:@"자료 없음"];
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
		[xmlValue release];
		[resultCode release];
		return;
	}
	
	NSXMLParser *parser = [[NSXMLParser alloc] initWithData:urlData];
	
	[parser setDelegate:self];
	[parser parse];
	[parser release];
	
	// 분석된 주소좌표 정보를 읽는다.
	//[self MyAlert:resultCode];
	if([resultCode isEqualToString:@"200"])
	{
		[self setAddress:resultCoord];
	}

	[xmlValue release];
	[resultCode release];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

}

// 키보드 Done 클릭 시 자판 안보이게 처리
-(IBAction)searchFieldDoneEditing:(id)sender
{
	[sender resignFirstResponder];
}

// 백그라운드 클릭 시 자판 안보이게 처리 - 미구현
- (IBAction)backgroundClick:(id)sender
{
	[searchField resignFirstResponder];
}

#pragma mark -
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	// 현재 위치 확인
	mapView.showsUserLocation = TRUE;	

	// 서울 시청
	CLLocationCoordinate2D location;
	location.latitude = 37.5665350;
	location.longitude = 126.9779692;
	
	MyAnnotation *mark = [[MyAnnotation alloc] initWithCoordinate:location];
	[mark setTitle:@"서울시청"];
	mark.subtitle = @"서브 타이틀";
	[mapView addAnnotation:mark];
	[mark release];

	[searchField setText:@"광명사거리역"];
	
	// 지도 표시
	[self setAddress:location];
	
}

// 주어진 주소좌표정보에 대한 지도를 표시한다.
- (void) setAddress: (CLLocationCoordinate2D) location
{
	// 확대 배율
	MKCoordinateRegion region;
	MKCoordinateSpan span;
	span.latitudeDelta = 0.02;
	span.longitudeDelta = 0.02;
	
	region.span = span;
	region.center = location;
	
	[mapView setRegion:region animated:TRUE];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[mapView release];
	[searchField release];
    [super dealloc];
}

@end
